#include "netlib/net/event/event_loop_thread.h"

#include "netlib/net/event/event_loop.h"

using std::string;

netlib::net::EventLoopThread::EventLoopThread(bool is_epoll,
                                              const ThreadInitCallBack& cb,
                                              const string& name) :
    thread_([this] { ThreadFunc(); }, name),
    is_epoll_(is_epoll) {}

netlib::net::EventLoopThread::~EventLoopThread() {
	if (loop_) {
		loop_->Quit();
		thread_.Join();
	}
}

netlib::net::EventLoop* netlib::net::EventLoopThread::StartLoop() {
	thread_.Start();
	MutexLockGuard lock(mutex_);
	while (!loop_) {
		cond_.Wait();
	}
	return loop_;
}

void netlib::net::EventLoopThread::ThreadFunc() {
	EventLoop loop(is_epoll_);
	if (init_cb_) {
		init_cb_(&loop);
	}

	{
		MutexLockGuard lock(mutex_);
		loop_ = &loop;
		cond_.Notify();
	}
	loop.Loop();
	MutexLockGuard lock(mutex_);
	loop_ = nullptr;
}
